import asyncio, random, math
from app.services.broker import dry_run

ICE_RESEND_SEC = 5      # 5 秒补一次
MAX_RETRY    = 5        # 最多重试 5 次

async def iceberg_worker(order_id: int):
    order = dry_run.get(order_id)
    remaining = order.qty
    while remaining > 0 and order.cancel_retry < MAX_RETRY:
        clip = min(order.visible_size, remaining)
        try:
            # 1. 挂露出单
            dry_run.execute(
                code=order.code,
                side=order.side,
                price=round(order.price * (1 + random.uniform(-0.001, 0.001)), 2),
                qty=clip
            )
            # 2. 模拟等待成交（Dry-Run 直接 sleep）
            await asyncio.sleep(ICE_RESEND_SEC)
            # 3. 假设成交 clip（真实环境用成交回报）
            remaining -= clip
        except Exception as e:
            print(f"[Iceberg] {order.id} clip failed: {e}, retry")
            order.cancel_retry += 1
            await asyncio.sleep(1)

    if remaining == 0:
        dry_run.status(order_id, 'filled')
    else:
        dry_run.status(order_id, 'cancelled')
